let user = ''
let videos = {}
let progress = document.querySelector('#progress')
let total = 0

async function isDir(path) {
    if (!path.endsWith('/')) {
        path += '/';
    }
    let res = await cockpit.spawn(['ls', '-d', path])
        .catch((error) => {
            return false;
        });
    if (!res) {
        return false;
    }
    return true;
}

async function init() {
    user = await cockpit.user();
    if (!user) {
        alert('无法获取用户名');
        return;
    }
    let homeDir = user.home;
    let res = await cockpit.spawn(['ls', homeDir + '/resources/Downloads/'])
        .catch((error) => {
            alert('无法访问Downloads目录');
            return false;
        });
    if (!res) {
        return;
    }
    for (let item of res.split(/\s+/)) {
        if (item !== '' && await isDir(homeDir + '/resources/Downloads/' + item)) {
            let item2s = await cockpit.spawn(['ls', homeDir + '/resources/Downloads/' + item + '/'])
                .catch((error) => {
                    console.log('无法访问视频目录');
                });
            if (!item2s) {
                continue;
            }
            for (let item2 of item2s.split(/\s+/)) {
                if (item2 !== '' && await isDir(homeDir + '/resources/Downloads/' + item + '/' + item2)) {
                    let baseDir = homeDir + '/resources/Downloads/' + item + '/' + item2 + '/';
                    let json = await cockpit.file(baseDir + 'entry.json').read()
                        .catch((error) => {
                            console.log('无法读取entry.json');
                        });
                    if (json) {
                        let info = JSON.parse(json);
                        let item3 = await cockpit.spawn(['ls', baseDir])
                            .catch((error) => {
                                console.log('无法访问视频目录');
                            });
                        for (let item4 of item3.split(/\s+/)) {
                            if (item4 !== '' && await isDir(baseDir + item4)) {
                                let files = await cockpit.spawn(['ls', baseDir + item4])
                                for (let file of files.split(/\s+/)) {
                                    if (file.endsWith('m4s')) {
                                        title = (info.title + '_' + info.page_data.page).replace(/\s/g, '_').replace(/\//g, '_')
                                        if (videos[title] === undefined) {
                                            videos[title] = []
                                            total++
                                            progress.textContent = `正在初始化 [${total}]`
                                        }
                                        videos[title].push(baseDir + item4 + '/' + file)
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

init()
    .then(() => {
        let resources = document.querySelector('#videoTableBody')
        for (let item in videos) {
            let tr = document.createElement('tr')
            let td1 = document.createElement('td')
            td1.textContent = item
            let td2 = document.createElement('td')
            for (let file of videos[item]) {
                td2.innerHTML += `${file}<br />`
            }
            tr.appendChild(td1)
            tr.appendChild(td2)
            resources.appendChild(tr)
        }
        document.querySelector('#mergeButton').addEventListener('click', async () => {
            let count = 1
            let errors = 0
            for (let item in videos) {
                document.querySelector('#statusInfo').textContent = `正在合并视频(${count}/${total})`
                let args = ['ffmpeg']
                for (let file of videos[item]) {
                    args.push('-i')
                    args.push(file)
                }
                args.push('-codec')
                args.push('copy')
                args.push(`${user.home}/resources/Downloads/${item}.mp4`)
                progress.textContent = `正在合并 ${item}`
                let res = await cockpit.spawn(args)
                    .catch(err => {
                        errors++
                        return false
                    })
                if (res !== false) {
                    let rfile = videos[item][0].split('/').slice(1, 7).join('/')
                    await cockpit.spawn(['rm', '-rf', rfile])
                        .catch(err => {
                            return false
                        })
                    rfile = videos[item][0].split('/').slice(1, 6).join('/')
                    let res = await cockpit.spawn(['ls', rfile])
                        .catch(err => {
                            return false
                        })
                    if (!res || res.trim() === '') {
                        await cockpit.spawn(['rm', '-rf', rfile])
                            .catch(err => {
                                return false
                            })
                    }
                }
                count++
            }
            progress.textContent = `合并完成，共有${errors}个错误`
            videos = {}
            init()
                .then(() => {
                    let resources = document.querySelector('#videoTableBody')
                    resources.innerHTML = ''
                    for (let item in videos) {
                        let tr = document.createElement('tr')
                        let td1 = document.createElement('td')
                        td1.textContent = item
                        let td2 = document.createElement('td')
                        for (let file of videos[item]) {
                            td2.innerHTML += `${file}<br />`
                        }
                        tr.appendChild(td1)
                        tr.appendChild(td2)
                        resources.appendChild(tr)
                    }
                })
            document.querySelector('#statusInfo').textContent = '准备就绪，可以开始合并视频'
        })
        progress.textContent = '初始化完成'
        document.querySelector('#statusInfo').style = 'display: block;'
    })